# Maintainer: Christoph Reiter <reiter.christoph@gmail.com>

_realname=rav1e
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=0.6.6
pkgrel=2
pkgdesc='An AV1 encoder focused on speed and safety (mingw-w64)'
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32' 'clangarm64')
url=https://github.com/xiph/rav1e/
license=('spdx:BSD-2-Clause')
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs")
makedepends=("${MINGW_PACKAGE_PREFIX}-rust"
             "${MINGW_PACKAGE_PREFIX}-cargo-c"
             $([[ "${CARCH}" == "aarch64"  ]] || echo "${MINGW_PACKAGE_PREFIX}-nasm"))
source=("${_realname}-${pkgver}.tar.gz"::"https://github.com/xiph/rav1e/archive/v${pkgver}.tar.gz"
        https://github.com/xiph/rav1e/releases/download/v${pkgver}/Cargo.lock)
sha256sums=('723696e93acbe03666213fbc559044f3cae5b8b888b2ddae667402403cff51e5'
            '2014f7d76e7d0d7eaa63158ef5a1a1cea15a095fd5fb79b20b1052015a7fcd0c')

prepare() {
  cp Cargo.lock "${_realname}-${pkgver}"
  cd "${srcdir}/${_realname}-${pkgver}"

  cargo vendor \
    --locked \
    --versioned-dirs

  mkdir -p .cargo
  cat >> .cargo/config.toml <<END
[source.crates-io]
replace-with = "vendored-sources"

[source.vendored-sources]
directory = "vendor"
END


  sed -i -e 's/"cfg(all(target_arch = \\"\([^\\]\+\)\\", target_env = \\"gnu\\", target_abi = \\"llvm\\", not(windows_raw_dylib)))"/"\1-pc-windows-gnullvm"/g' \
    "vendor/windows-targets-0.48.0/Cargo.toml"
  sed -i -e 's/\("Cargo.toml":\)"[^"]\+"/\1"'"$(sha256sum "vendor/windows-targets-0.48.0/Cargo.toml" | cut -d' ' -f1)"'"/' \
    "vendor/windows-targets-0.48.0/.cargo-checksum.json"
}

build() {
  cd "${srcdir}/${_realname}-${pkgver}"

  export WINAPI_NO_BUNDLED_LIBRARIES=1
  cargo build \
    --release \
    --frozen \
    --offline

  MSYS2_ARG_CONV_EXCL="--prefix=" \
    cargo capi build \
      --release \
      --frozen \
      --library-type=cdylib \
      --prefix="${MINGW_PREFIX}"
}

check() {
  cd "${srcdir}/${_realname}-${pkgver}"

  cargo test \
    --release \
    --frozen
}

package() {
  cd "${srcdir}/${_realname}-${pkgver}"

  cargo install \
    --frozen \
    --offline \
    --no-track \
    --path . \
    --root "${pkgdir}${MINGW_PREFIX}"

  MSYS2_ARG_CONV_EXCL="--prefix=" \
    cargo capi install \
      --release \
      --frozen \
      --library-type=cdylib \
      --prefix="${MINGW_PREFIX}" \
      --destdir="${pkgdir}"

  # Remove def file
  rm -f ${pkgdir}${MINGW_PREFIX}/lib/*.def

  install -Dm644 LICENSE PATENTS -t "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/"
}
